package com.gcxy.tour.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gcxy.tour.common.CommException;
import com.gcxy.tour.common.JdbcUtils;
import com.gcxy.tour.domain.UserInfo;

/**
 * 内容：用户 User信息的 增 删 改 查
 * @author 方昆
 *
 */
public class UserInfoDao {

	
private Logger logger=LoggerFactory.getLogger(getClass());
	
	private UserInfo rowMap(ResultSet rs) throws SQLException {
		UserInfo user=new UserInfo();
		user.setId((long) rs.getInt("id"));
		user.setPassword(rs.getString("password"));
		user.setUsername(rs.getString("Username"));
		user.setUsercode(rs.getString("Usercode"));
		user.setUserphone(rs.getString("Userphone"));
		return user;
	}
	/**
	 * 根据账号在数据库中查询该用户信息
	 * @param usercode
	 * @return
	 */
	public UserInfo findByCode(String usercode) {
		Connection conn=JdbcUtils.getConnection();
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			String sql="select * from user where usercode=?";
			ps=conn.prepareStatement(sql);
			ps.setString(1, usercode);
			
			logger.debug(sql);
			
			rs=ps.executeQuery();
			while (rs.next()) {
				return rowMap(rs);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new CommException(e.getMessage());
		} finally {
			JdbcUtils.close(conn, ps, rs);
		}
		return null;
	}
	/**
	 * 根据账号修改数据库表的记录
	 * @param user
	 */
	public void update(UserInfo user) {
		Connection conn=JdbcUtils.getConnection();
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			String sql="update user set username=?,password=? where usercode=?";
			ps=conn.prepareStatement(sql);
			ps.setString(1, user.getUsername());
			ps.setString(2, user.getPassword());
			ps.setString(3, user.getUsercode());
			
			logger.debug(sql);
			
			if(ps.executeUpdate()<1) {
				throw new CommException("修改数据失败");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new CommException(e.getMessage());
		} finally {
			JdbcUtils.close(conn, ps, rs);
		}
		
	}
	/**
	 * 往数据库中插入用户信息 username,password,usercode
	 * @param UserInfo
	 */
	public void insert(UserInfo user) {
		Connection conn=JdbcUtils.getConnection();
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			String sql="insert into user(username,password,usercode) values(?,?,?)";
			ps=conn.prepareStatement(sql);
			ps.setString(1, user.getUsername());
			ps.setString(2, user.getPassword());
			ps.setString(3, user.getUsercode());
			
			logger.debug(sql);
			
			if(ps.executeUpdate()<1) {
				throw new CommException("插入数据失败");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new CommException(e.getMessage());
		} finally {
			JdbcUtils.close(conn, ps, rs);
		}
	}

}
